<template>
  <div class="list-table">
    <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.prevent.native>
      <el-form-item :label="$t('科目名称')" prop="keyName">
        <el-input
          v-model="queryParams.keyName"
          :placeholder="$t('科目名称')"
          clearable
          :onsubmit="false"
          @keyup.enter.native="queryHandle"
        />
      </el-form-item>
      <el-form-item :label="$t('表类型')" prop="tableType">
        <el-select v-model="queryParams.tableType" :placeholder="$t('表类型')" clearable>
          <el-option
            v-for="dict in tableTypeOptions"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['company:pcw:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-upload
          class="upload-demo"
          :headers="uploadHeaders"
          :action="ocrBaseUrl"
          :show-file-list="true"
          :on-success="ocrUploadSuccess"
          :auto-upload="true"
          :limit="3"
          accept=".xls, .xlsx, .pdf, image/*"
          style="color: #1890ff;"
        > -->
        <el-button
          v-hasPermi="['company:pcw:edit']"
          icon="el-icon-upload"
          size="mini"
          type="warning"
          @click="uploadHandle"
        >{{ $t('导入') }}</el-button>

        <!-- </el-upload> -->
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          v-hasPermi="['company:pcw:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>-->

    </el-row>

    <el-table
      v-loading="loading"
      :data="pcwTempSubjectList"
      default-expand-all
      row-key="id"
      border
    >
      <el-table-column :label="$t('科目名称')" align="left" prop="keyName">
        <template slot-scope="scope">
          <span>{{ $t(scope.row.keyName) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('财报类型')" align="center" prop="tableType" :formatter="tableTypeFormat" />
      <el-table-column :label="$t('排序')" align="center" prop="keySort" />
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <div v-if="scope.row.pid !=='0'">
            <el-button
              v-hasPermi="['company:pcw:edit']"
              size="small"
              type="text"
              icon="el-icon-edit"
              @click="updateHandle(scope.row)"
            >{{ $t('修改') }}</el-button>
            <el-button
              v-hasPermi="['company:pcw:remove']"
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="deleteHandle(scope.row)"
            >{{ $t('删除') }}</el-button>
          </div>
          <div v-else>
            <el-button
              v-hasPermi="['company:pcw:edit']"
              size="small"
              type="text"
              icon="el-icon-plus"
              @click="addBottom(scope.row)"
            >{{ $t('新增下级') }}</el-button>
          </div>

        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改公司财务数据科目模版对话框 -->
    <el-dialog :title="$t('公司财务数据科目模版')" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <pcwTempSubjectForm ref="pcwTempSubjectForm" :company-id="companyId" />
    </el-dialog>

    <!-- 财报识别 -->
    <el-dialog :title="$t('财报识别结果')" :visible.sync="ocrFormOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <pcwOcrResult ref="pcwOcrResult" />
    </el-dialog>
    <!-- 添加或修改上传财务数据主表对话框 -->
    <el-dialog
      :title="$t('科目信息上传')"
      :visible.sync="uploadFormOpen"
      width="30%"
      :close-on-click-modal="false"
      :lock-scroll="false"
      append-to-body
    >
      <pcwDataSubjectUpload ref="pcwDataSubjectUpload" :type-id="form.typeId" :is-sys-temp="false" :company-id="form.companyId" />
    </el-dialog>
  </div>
</template>

<script>
import {
  delPcwTempSubject,
  exportPcwTempSubject,
  saveOcrResult,
  matchSubjectTree
} from '@/api/company/pcw/pcwTempSubject'
import { pcwReportIdentify } from '@/api/company/pcw/pcwDataMain'
import pcwTempSubjectForm from './pcwTempSubjectForm.vue'
import pcwDataSubjectUpload from './pcwDataSubjectUpload.vue'
import pcwOcrResult from './pcwOcrResult.vue'
import { getToken } from '@/utils/auth'
import { config } from '@/utils'
export default {
  components: {
    pcwTempSubjectForm,
    pcwOcrResult,
    pcwDataSubjectUpload
  },
  props: {
    companyId: {
      type: String,
      default: ''
    }
  },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 公司财务数据科目模版表格数据
          pcwTempSubjectList: [],
          // 弹出层标题
          title: '',
          // 是否显示弹出层
          formOpen: false,
          // 表类型字典
          tableTypeOptions: [],
          // 查询参数
          queryParams: {
              companyId: this.companyId || this.$route.query.id,
              typeId: this.$route.query.typeId,
              keyName: undefined,
              tableType: undefined
          },
          // 表单参数
          form: {
            subjects: [],
            pdList: [],
            cfList: [],
            bsList: [],
            companyId: this.companyId,
            typeId: this.$route.query.typeId
          },
          // 上传的图片
          ocrFileAtt: undefined,
          // 附件识别open
          ocrFormOpen: false,
          // 附件识别title
          ocrTitle: '',
          // 附件上传地址
          uploadHeaders: { Authorization: 'Bearer ' + getToken() },
          // excel后台上传地址
          ocrBaseUrl: config.baseURL + '/pcw/pcwDataMain/uploadSubject',
          // 上传
          uploadFormOpen: false
      }
  },
  watch: {
    companyId: {
      handler(val) {
        if (val) {
          this.queryParams.companyId = val
          this.getList()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getDicts('pcw_table_type').then(response => {
        this.tableTypeOptions = response.data
    })
  },
  mounted() {
    this.getList()
  },
  methods: {
    // OCR文件上传成功，触发此函数
    ocrUploadSuccess(resp, file, fileList) {
      if (resp.code === 200) {
        this.openPcwOcr(resp)
        // 判断是否有匹配科目
      } else {
        this.msgError(resp.msg)
      }
      fileList.splice(fileList.length - 1, 1)
    },
    // 财务识别完成之后打开财务识别弹窗
    openPcwOcr(resp) {
      this.ocrFormOpen = true
      this.$nextTick(() => {
        this.$refs.pcwOcrResult.form.pdList = resp.datas.pdList
        this.$refs.pcwOcrResult.form.cfList = resp.datas.cfList
        this.$refs.pcwOcrResult.form.bsList = resp.datas.bsList
        this.$refs.pcwOcrResult.source = 'temp'
      })
    },
    // 财报识别并且展示数据
    uploadOcrFile() {
      if (this.ocrFileAtt !== null && this.ocrFileAtt.size > 0) {
        const formData = new FormData()
        formData.append('file', this.ocrFileAtt)
        this.loading = true
        pcwReportIdentify(formData).then(response => {
          if (response.code === 200) {
            this.ocrFormOpen = true
            this.$nextTick(() => {
              this.$refs.pcwOcrResult.form.pdList = response.datas.pdList
              this.$refs.pcwOcrResult.form.cfList = response.datas.cfList
              this.$refs.pcwOcrResult.form.bsList = response.datas.bsList
            })
            this.loading = false
            // 判断是否有匹配科目
          } else {
            this.msgError(response.msg)
          }
        })
      }
    },
    /** 查询公司财务数据科目模版列表 */
    getList() {
      this.loading = true
      matchSubjectTree(this.queryParams).then(response => {
            this.pcwTempSubjectList = response.rows
            this.loading = false
        })
    },
    // 表类型字典翻译
    tableTypeFormat(row) {
      return this.selectDictLabel(this.tableTypeOptions, row.tableType)
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            companyId: this.companyId,
            typeId: this.$route.query.typeId,
            keyName: undefined,
            keyCode: undefined,
            keySort: undefined,
            tableType: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined,
            remark: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
            this.$refs.pcwTempSubjectForm.init(null)
        })
    },
    /** 新增按钮操作 */
    addBottom(row) {
        this.formOpen = true
        this.$nextTick(() => {
          this.$refs.pcwTempSubjectForm.form.tableType = row.tableType
          this.$refs.pcwTempSubjectForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.pcwTempSubjectForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delPcwTempSubject(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return exportPcwTempSubject(queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(function() {
        })
    },
    // 保存财报识别结果
    saveOcrResult() {
      this.loading = true
      this.form.subjects = []
      this.form.subjects.push(this.form.bsList)
      this.form.subjects.push(this.form.pdList)
      this.form.subjects.push(this.form.cfList)
      this.form.subjectJson = JSON.stringify(this.form.subjects)
      saveOcrResult(this.form).then(response => {
        if (response.code === 200) {
          this.getList()
        } else {
          this.msgError(response.msg)
          this.loading = false
        }
      })
    },
    uploadHandle() {
        this.uploadFormOpen = true
    }
  }
}
</script>
